package fr.efrei.tradesys.treatments;

import java.math.BigDecimal;
import java.math.RoundingMode;

import fr.efrei.tradesys.hibernate.beans.Currency;
import fr.efrei.tradesys.hibernate.beans.Rate;
import fr.efrei.tradesys.hibernate.factory.DaoFactory;

public class Converter
{

	public double convertCurrenciesSell(double units, Currency from, Currency to)
	{
		Rate r = DaoFactory.getInstance().getRateDao().getRate(from, to);
		if (r != null)
		{
			return new BigDecimal(units * r.getBid()).setScale(2,
					RoundingMode.HALF_EVEN).doubleValue();
		}
		else
		{
			r = DaoFactory.getInstance().getRateDao().getRate(to, from);
			return new BigDecimal(units / r.getAsk()).setScale(2,
					RoundingMode.HALF_EVEN).doubleValue();
		}
	}

	public double convertCurrenciesBuy(double units, Currency from, Currency to)
	{
		Rate r = DaoFactory.getInstance().getRateDao().getRate(from, to);
		if (r != null)
		{
			return new BigDecimal(units * r.getAsk()).setScale(2,
					RoundingMode.HALF_EVEN).doubleValue();
		}
		else
		{
			r = DaoFactory.getInstance().getRateDao().getRate(to, from);
			return new BigDecimal(units / r.getBid()).setScale(2,
					RoundingMode.HALF_EVEN).doubleValue();
		}
	}

}
